/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react/jsx-key */
import ProForm, {
  ProFormSelect,
} from '@ant-design/pro-form';
import { Button } from 'antd'
import { useEffect, useState, useRef } from 'react';
import { getPrinter, updatePrinter } from '@/utils/storage'

const Setting = () => {

  const { ipcRenderer } = window.electron
  const [printers, setPrinters] = useState([])
  const [printerOpts, setPrintersOpts] = useState([])
  const [printer, setPrinter] = useState({})

  const formRef = useRef();

  useEffect(() => {

    const pstr = getPrinter()
    if (pstr) {
      const pter = JSON.parse(pstr)
      setPrinter(pter)
      setPrinterSelect(pter.name)
    }

    ipcRenderer.once('return-printers', (params) => {
      let prts = []
      let opts = []
      for (const pt of params) {
        const { name, status } = pt
        if (0 !== status) {
          return
        }
        opts.push({
          label: name,
          value: name,
          key: name
        })
        prts.push(pt)
      }
      setPrintersOpts(opts)
      setPrinters(prts)
    });

    ipcRenderer.send('get-printers');
  }, []);

  const getPrinterByName = (name) => {
    const result = printers.filter((p) => {
      return p.name === name
    })
    return result && result.length > 0 ? result[0] : undefined
  }

  const setPrinterSelect = (name) => {
    let fileds = formRef.current.getFieldsValue()
    fileds.printer = name
    formRef.current.setFieldsValue(fileds)
  }

  return (
    <ProForm
      submitter={{
        // 完全自定义整个区域
        render: (props, doms) => {
          return [
            <Button type="primary" onClick={() => {
              const { printer } = props.form.getFieldsValue()
              const p = getPrinterByName(printer)
              if (p)
                updatePrinter(p)
            }}>Save</Button>
          ];
        },
      }}
      style={{ padding: '20px' }}
      initialValues={{
      }}
      autoFocusFirstInput
      formRef={formRef}
    >
      <ProForm.Group>
        <ProFormSelect
          options={printerOpts}
          width="md"
          name="printer"
          label="Select Printer"
          placeholder="Please select printer"
        />
      </ProForm.Group>
    </ProForm>
  )
}

export default Setting
